package com.kinglone.back.sysmenu.controller;

import com.kinglone.back.sysmenu.model.SysMenu;
import com.kinglone.back.sysmenu.service.SysMenuService;
import com.kinglone.common.entity.PageBean;
import com.kinglone.common.node.ZTreeNode;
import com.kinglone.common.utils.ResponseUtil;
import com.kinglone.common.utils.ResultMsg;
import com.kinglone.common.utils.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sysMenu")
public class SysMenuController {
	protected final static Logger logger = LogManager.getLogger(SysMenuController.class);

	@Autowired
	private SysMenuService sysMenuService;

	@RequestMapping("/showmenu")
	public String showmenu(HttpServletRequest request){
		logger.info("跳转到菜单列表");
		return "sysmenu/menuList";
	}
	@RequestMapping("/showMenuAdd")
	public String showMenuAdd(HttpServletRequest request){
		logger.info("跳转到添加菜单");
		return "sysmenu/menuAdd";
	}

	@RequestMapping("/menulist")
	public String menulist(String page, String limit,String key, HttpServletResponse response){
		logger.info("----------------------查询菜单列表信息");
		try {
			PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(limit));
			JSONObject result = new JSONObject();

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("key",key);
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());

			List<SysMenu> menulist = sysMenuService.list(map);
			int count = sysMenuService.getTotal(map);
			JSONArray jsonArray = JSONArray.fromObject(menulist);
			result.put("code",0);
			result.put("msg","");
			result.put("data", jsonArray);
			result.put("count", count);
			ResponseUtil.write(response, result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping("/addMenu")
	@ResponseBody
	public ResultMsg addMenu(SysMenu sysMenu){
		ResultMsg msg = new ResultMsg();
		if(StringUtils.isEmpty(sysMenu.getTitle())){
			msg.setSuccess(false);
			msg.setMessage("菜单名称不能为空!");
			return msg;
		}
		if(StringUtils.isEmpty(sysMenu.getHref())){
			msg.setSuccess(false);
			msg.setMessage("菜单路径不能为空!");
			return msg;
		}
		try {
			msg = sysMenuService.addMenu(sysMenu);
		}catch (Exception e){
			e.printStackTrace();
			msg.setSuccess(false);
			msg.setMessage("菜单保存失败!");
			return msg;
		}
		return msg;
	}

	@RequestMapping("/delMenu")
	@ResponseBody
	public ResultMsg delMenu(@RequestParam("id") String id){
        ResultMsg msg = new ResultMsg();
        try {
             sysMenuService.delMenu(id);
            msg.setSuccess(true);
            msg.setMessage("菜单删除成功!");
        }catch (Exception e){
            e.printStackTrace();
            msg.setSuccess(false);
            msg.setMessage("菜单删除失败!");
            return msg;
        }
        return msg;
    }

	/**
	 * 获取首页菜单
	 * @param topMenu
	 * @return
	 */
	@RequestMapping("/navs")
	@ResponseBody
	public ResultMsg navs(@RequestParam("topMenu")String topMenu){
		ResultMsg msg = new ResultMsg();
		try {
			logger.info("根据一级菜单获取二级菜单，一级菜单为：topMenu："+topMenu);
			JSONObject jsonData = new JSONObject();
			JSONArray jsonArrayData = new JSONArray();
			List<SysMenu> menus = sysMenuService.getMenuByTopMenu(topMenu);
			for (int i=0;i<menus.size();i++){
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("title",menus.get(i).getTitle());
				jsonObject.put("icon",menus.get(i).getIcon());
				jsonObject.put("href",menus.get(i).getHref());
				jsonObject.put("spread",menus.get(i).getSpread());
				jsonArrayData.add(jsonObject);
			}
			jsonData.put(topMenu,jsonArrayData);
			logger.info("查询到的二级菜单为:"+jsonData);
			msg.setData(jsonData);
			msg.setSuccess(true);
		}catch (Exception e){
			e.printStackTrace();
			msg.setSuccess(false);
			msg.setMessage("加载失败!");
			return msg;
		}
		return msg;
	}

	/**
	 * 获取角色列表
	 */
	@RequestMapping(value = "/menuTreeListByRoleId/{roleId}")
	@ResponseBody
	public List<ZTreeNode> menuTreeListByRoleId(@PathVariable Integer roleId) {
		//根据角色获取菜单列表
		List<Long> menuIds = sysMenuService.getMenuIdsByRoleId(roleId);
		if (StringUtil.isEmpty(menuIds)) {
			List<ZTreeNode> roleTreeList = sysMenuService.menuTreeList();
			return roleTreeList;
		} else {
			List<ZTreeNode> roleTreeListByUserId = sysMenuService.menuTreeListByMenuIds(menuIds);
			return roleTreeListByUserId;
		}
	}
}
